package com.jsptpd.smartauth.modules.business.restcontrol;


import com.jsptpd.smartauth.common.util.DateUtil;
import com.jsptpd.smartauth.common.util.HashUtils;
import com.jsptpd.smartauth.common.util.HttpUtils;
import com.jsptpd.smartauth.modules.business.model.RespObj;
import com.jsptpd.smartauth.modules.business.model.User;
import com.jsptpd.smartauth.modules.business.service.IBindService;
import com.jsptpd.smartauth.modules.business.service.IUserService;
import com.jsptpd.smartauth.modules.business.utils.Constants;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Calendar;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;


/**
 * 统一登录管理
 */
@Controller
@RequestMapping("/")
public class BindController {

    @Autowired
    IBindService bindService;
    @Autowired
    IUserService userService;

    @Autowired
    private HttpServletResponse httpServletResponse;
    @Autowired
    private HttpServletRequest httpServletRequest;

    @Value("${config.url.bindWx}")
    String bindWxUrl;
    @Value("${config.url.afterBind}")
    String afterBindUrl;
    @Value("${config.bind.appId}")
    String bindAppId;
    @Value("${config.url.checkProp}")
    private String checkProp;
    @Value("${config.bind.commpwd}")
    private String bindPwd;
    @Value("${config.url.bindQr}")
    private String bindQrUrl;
    @Value("${config.url.bindQrCallBack}")
    private String bindQrCallBack;
    @Value("${config.bind.wxExpire}")
    private int wxExpireTime;

    /**
     * 微信回调cpdat的绑定，历史接口暂不可修改，现在重定向到bind/wxqr：登录后扫码绑定
     */
    @ApiOperation(value="微信回调cpdat的绑定", notes="redirect，不必测")
    @RequestMapping(value = "bind", method = RequestMethod.GET)
    public String bind(@RequestParam String code, @RequestParam String state){
        return "redirect:"+String.format(bindWxUrl,code,state,bindAppId,Constants.WX_BIND_MODE_UNORDER);
    }

    /**
     * bind/order:微信回调预约绑定
     */
    @ApiOperation(value="邀请绑定回调", notes="redirect，不必测")
    @RequestMapping(value = "bind2", method = RequestMethod.GET)
    public String bindOrder(@RequestParam String code, @RequestParam String state){
        return "redirect:"+String.format(bindWxUrl,code,state,bindAppId,Constants.WX_BIND_MODE_ORDER);
    }

    /**
     * bind/wxqr：扫码绑定:0--未预约,1--预约
     */
    @ApiOperation(value="微信扫码绑定", notes="微信扫码绑定")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "code", value = "微信用户授权码", required = true, dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "state", value = "回传参数userId", required = true, dataType = "String",paramType = "query")
    })
    @RequestMapping(value = "bind/wxqr", method = RequestMethod.GET)
    public Object bindWxQr(@RequestParam String code,
                                 @RequestParam String state,
                                 @RequestParam(required = false) String appId,
                                 @RequestParam(required = false) String orderMode) throws IOException {
        if(appId==null || appId.isEmpty()){
            appId = bindAppId;
        }
        int order = Constants.WX_BIND_MODE_UNORDER;
        try{
            order = Integer.valueOf(orderMode);
        }catch(Exception e){
        }

        RespObj<String> respData = bindService.bindWechat(code, state, appId,order);

        if(respData!=null && respData.getError().getErrCode()==Constants.COMMON_ERRCODE_SUCC
                && order==Constants.WX_BIND_MODE_ORDER){
            //完善个人信息
            return "redirect:"+String.format(afterBindUrl,state);
        }

        ModelAndView view = new ModelAndView();
        view.setViewName("tips");
        view.addObject("result", respData.getError().getErrMessage());
        return view;
    }

    /**
     *  查询userId是否绑定过微信
     */
    @ApiOperation(value="查询userId是否绑定过微信", notes="true-已绑定有效")
    @ApiImplicitParam(name = "userId", value = "用户userId", required = true, dataType = "String",paramType = "query")
    @ResponseBody
    @RequestMapping(value = "bind/query", method = RequestMethod.GET)
    public Boolean bindQuery(@RequestParam String userId){
        RespObj<String> result = bindService.bindQueryUserId(userId);
        if(result!=null && result.getError().getErrCode()==Constants.COMMON_ERRCODE_SUCC){
            return true;
        }
        return false;
    }

    /**
     * bind/wx:app登录后绑定:属于未预约
     */
    @ApiOperation(value="app登录后绑定", notes="暂未使用")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "code", value = "微信用户授权码", required = true, dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "state", value = "回传参数userId", required = true, dataType = "String",paramType = "query")
    })
    @ResponseBody
    @RequestMapping(value = "bind/wx", method = RequestMethod.GET)
    public RespObj<String> bindWx(@RequestParam String code, @RequestParam String state) throws IOException {
        String appId = httpServletRequest.getHeader(Constants.AUTH_HEADTAG_APPID);
        RespObj<String> respData = bindService.bindWechat(code, state, appId,Constants.WX_BIND_MODE_UNORDER);

        return respData;
    }


    @Autowired
    RestTemplate restTemplate;

    /**
     * 生成预约绑定二维码：邀请码
     */
    @ApiOperation(value="生成预约绑定二维码：邀请码", notes="用户类型：0-外协，1-员工")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户名", required = true, dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "employeeType", value = "用户类型", required = true, dataType = "int",paramType = "query"),
    })
    @ResponseBody
    @RequestMapping(value="/bind/order",method = RequestMethod.GET)
    public RespObj<String> bindOrder(@RequestParam String userId,@RequestParam int employeeType) throws UnsupportedEncodingException {
        //String appId = httpServletRequest.getHeader(Constants.AUTH_HEADTAG_APPID);
        //预约绑定记录
        RespObj<String> respData = bindService.bindOrder(userId,employeeType,checkProp);

        if(respData!=null && respData.getError().getErrCode()==Constants.WX_BIND_ERRCODE_SUCC){
            //如果是外协，将新生成的用户名录入到user表
            if(employeeType==Constants.EMPLOYEE_TYPE_WX){
                User newUser = new User();
                newUser.setUserId(respData.getData());
                newUser.setPassword(HashUtils.shaPwd(bindPwd));
                newUser.setExpirationDate(DateUtil.getNewDate(new Date(),wxExpireTime, Calendar.MONTH));
                userService.updateUser(newUser);
            }
            //生成预约绑定二维码:注意微信回调地址urlencode，所以要分开格式化
            String callBackUrl = HttpUtils.getUrlEncode(bindQrCallBack);
            String orderUrl = String.format(bindQrUrl,callBackUrl,respData.getData());
            respData.setData(orderUrl);
        }

        return respData;
    }

    /**
     * test
     */
    @ApiOperation(value="邀请绑定成功的页面", notes="临时测试页面，后续替换")
    @RequestMapping(value = "bind/regist", method = RequestMethod.GET)
    public ModelAndView bindRegist(@RequestParam String userId) throws IOException {
        ModelAndView view = new ModelAndView();
        view.setViewName("regist");
        view.addObject("result", userId);
        return view;
    }

    @ApiOperation(value="邀请自动生成二维码", notes="临时测试页面")
    @RequestMapping(value = "bind/testOrder", method = RequestMethod.GET)
    public Object testOrder(@RequestParam String userId,@RequestParam int employeeType) throws IOException {
        RespObj<String> respData = bindOrder(userId,employeeType);
        if(respData!=null && respData.getError().getErrCode()==Constants.WX_BIND_ERRCODE_SUCC){
            return "redirect:"+respData.getData();
        }

        ModelAndView view = new ModelAndView();
        view.setViewName("tips");
        view.addObject("result", respData.getError().getErrMessage());
        return view;
    }
}